import { _decorator, Component, Node } from 'cc'
import { EntityManager } from './EntityManager'
import { DIRECTION_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_ENUM } from '../Enum'
import EventManager from '../Runtime/EventManager'
import DataManager from '../Runtime/DataManager'
import { IEntity } from '../Levels'
const { ccclass, property } = _decorator

/**
 * Predefined variables
 * Name = EnemyManager
 * DateTime = Fri Jul 22 2022 10:40:19 GMT+0800 (中国标准时间)
 * Author = Zero_Y
 * FileBasename = EnemyManager.ts
 * FileBasenameNoExtension = EnemyManager
 * URL = db://assets/Base/EnemyManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('EnemyManager')
export class EnemyManager extends EntityManager {
  async init(params: IEntity) {
    super.init(params)
    // 角色创建完成 或者 角色移动 触发更新NPC方向
    EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection, this)
    EventManager.Instance.on(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection, this)
    this.onChangeDirection(true)
    // 死亡
    EventManager.Instance.on(EVENT_ENUM.ATTACK_ENEMY, this.onDead, this)
  }

  // 解绑事件
  onDestroy() {
    super.onDestroy()
    EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onChangeDirection)
    EventManager.Instance.off(EVENT_ENUM.PLAYER_BORN, this.onChangeDirection)
    EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onDead)
  }

  // NPC朝向角色检测
  onChangeDirection(isInit?: boolean) {
    if (this.state === ENTITY_STATE_ENUM.DEATH || !DataManager.Instance.player) {
      // 已死亡
      return
    }
    const { x: playerX, y: playerY } = DataManager.Instance.player
    const disX = Math.abs(this.x - playerX)
    const disY = Math.abs(this.y - playerY)
    // 如果disY = disX，表示在某个象限夹角处，如果 disY > disX 靠近Y轴，如果 disY < disX 则靠近X轴

    // 当人物在移动为对角线的时候，NPC不做转向操作
    if (disX === disY && !isInit) {
      return
    }

    if (playerX >= this.x && playerY <= this.y) {
      // 在第一象限
      if (disY > disX) {
        // 在第一象限0~45°夹角中 靠近Y轴，朝上
        this.direction = DIRECTION_ENUM.TOP
      } else {
        // 在第一象限45~90°夹角中 靠近X轴，朝右
        this.direction = DIRECTION_ENUM.RIGHT
      }
    } else if (playerX <= this.x && playerY <= this.y) {
      // 在第二象限
      if (disY > disX) {
        // 第二象限靠近Y轴，向上
        this.direction = DIRECTION_ENUM.TOP
      } else {
        // 第二象限靠近X轴，向左
        this.direction = DIRECTION_ENUM.LEFT
      }
    } else if (playerX <= this.x && playerY >= this.y) {
      // 在第三象限
      this.direction = disY > disX ? DIRECTION_ENUM.BOTTOM : DIRECTION_ENUM.LEFT
    } else if (playerX >= this.x && playerY >= this.y) {
      // 在第四象限
      this.direction = disY > disX ? DIRECTION_ENUM.BOTTOM : DIRECTION_ENUM.RIGHT
    }
  }

  // NPC死亡
  onDead(attackId: string) {
    if (this.state === ENTITY_STATE_ENUM.DEATH) {
      return
    }
    // 判断当前NPC死亡才死亡
    if (this.id === attackId) {
      this.state = ENTITY_STATE_ENUM.DEATH
    }
  }
}
